import { Router } from 'vue-router';
import { PAGE_NOT_FOUND_ROUTE } from '../routes/basic';
import { getTabList } from '../../hooks/setting/useUserSetting';
import { Validator } from './guardStrategy';
import { useUserStoreWithout } from '../../store/modules/user';
import { usePermissionStore } from '../../store/modules/permission';
import { SaaSUserMenuParams } from '../../api/sys/model/menuModel';
import ClientMonitor from 'skywalking-client-js';
import { getHomePathAndAddRoutes } from '../helper/routeHelper';
import { SaaSPageEnum } from '../../enums/pageEnum';

const validator = new Validator();

// eslint-disable-next-line max-lines-per-function
export default function createMenuGuard(router: Router) {
  const userStore = useUserStoreWithout();
  const userInfo = userStore.getUserInfo;
  const permissionStore = usePermissionStore();
  router.beforeEach(async (to, from, next) => {
    const shouldNext = validator.start(to, from);
    getTabList(to.path);
    if (shouldNext) {
      next();
      return;
    } else {
      // 需要刷新菜单的情况
      const buildRouteParams = {
        tenantCode: userInfo.tenantCode,
        userId: userInfo.userId,
      };
      let homePath = '';
      let routes = [];

      await permissionStore.fetchHashPower();
      routes = await permissionStore.buildRoutes(buildRouteParams as SaaSUserMenuParams);
      if (routes.length === 1) {
        // 这里是请求菜单失败了，默认只有一个加载失败的路由，一般是由于请求菜单401，
        // next(false)终止掉这一层的嵌套，防止覆盖返回登录页面的嵌套，导致无法返回登录页
        next(false);
      }
      homePath = getHomePathAndAddRoutes(routes, router);
      permissionStore.setDynamicAddedRoute(true);
      if (to.path === SaaSPageEnum.BASE_LOGIN) {
        // 当同时满足已加载菜单，并且需要返回登录页时，直接让用户免登录跳转至首页
        next({ path: homePath });
      } else if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
        // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
        next({ path: to.fullPath, replace: true, query: to.query });
      } else {
        const redirectPath = (from.query.redirect || to.path) as string;
        const redirect = decodeURIComponent(redirectPath);
        const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
        next(nextData);
      }
    }
  });
  router.afterEach((to) => {
    ClientMonitor.register({
      service: 'saaslanding-new-ui',
      pagePath: to.path,
      serviceVersion: 'v0.0.1',
      vue: 'Vue',
      useFmp: true,
      autoTracePerf: true,
      traceSDKInternal: true,
    });
  });
}
